// 处理content script的clickRadioButtons请求
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  console.log('Received message:', message);
  
  chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
    if (chrome.runtime.lastError) {
      console.error('Error querying tabs:', chrome.runtime.lastError);
      return;
    }
    
    if (tabs.length === 0 || !tabs[0].id) {
      console.error('No active tab found');
      return;
    }
    
    const tabId = tabs[0].id;
    
    if (message.action === 'updateMongoDBLinkClicked') {
      console.log('Requesting MongoDB link from content script', tabId);
      handleMongoDBLinkUpdate(tabId);
    } else if (message.action === 'reloginSellerClicked') {
      console.log('Relogin all seller end', tabId);
      reloginSeller(tabId);
    } else if (message.action === 'getSalesDataClicked') {
      console.log('Fetching sales data from all VPS');
      getSalesData();
    } else if (message.action === 'startDailyCrawlClicked') {
      console.log('Fetching daily data from all VPS');
      startDailyCrawl();
    } else if (message.action === 'pullTemuSpidersClicked') {
      console.log('Pulling TemuSpiders code from all VPS');
      pullTemuSpiders();
    } else if (message.action === 'restartServerClicked') {
      console.log('Restarting server');
      restartServerTask();
    } else if (message.action === 'clickRadioButtons' || message.action === 'rejectClicked') {
      console.log('Sending clickRadioButtons message', tabId);
      chrome.tabs.sendMessage(tabId, { action: 'clickRadioButtons' });
    } else if (message.action === 'closeMessageClicked') {
      console.log('Sending closeMessages message', tabId);
      chrome.tabs.sendMessage(tabId, { action: 'closeMessages' });
    } else if (message.action === 'sumRealtimeSoldClicked') {
      console.log('Sending sumRealtimeSold message', tabId);
      chrome.tabs.sendMessage(tabId, { action: 'sumRealtimeSold' });
    } else if (message.action === 'rejectAllAdjustment') { 
      console.log('Sending rejectAllAdjustment message', tabId);
      chrome.tabs.sendMessage(tabId, { action: 'rejectAllAdjustment' });
    } else if (message.action === 'adjustPriceClicked') {
      console.log('Starting adjustPrice process');
      adjustPrice();
    } else if (message.action === 'previewAllPagesClicked') {
      console.log('Starting previewAllPages process');
      previewAllPages(tabId);
    } else if (message.action === 'addSerialNumber') {
      console.log('Starting addSerialNumber process');
      addSerialNumber(tabId, message.spuIds, message.serialNumber);
    } else if (message.action === 'getSkuCost') {
      console.log('Fetching SKU cost data', message.skc, message.sku);
      fetchSkuCost(message.skc, message.sku)
        .then(data => sendResponse(data))
        .catch(error => {
          console.error('Error fetching SKU cost:', error);
          sendResponse({error: error.message});
        });
      return true; // 保持消息通道打开以便异步响应
    } else if (message.action === 'getSkuCostsAndStocks') {
      console.log('Fetching SKU costs data', message.skuList.length);
      fetchSkuCostsAndStocks(message.skuList)
        .then(data => sendResponse(data))
        .catch(error => {
          console.error('Error fetching SKU costs:', error);
          sendResponse({error: error.message});
        });
      return true; // 保持消息通道打开以便异步响应
    }
  });
  return true; // 保持消息通道打开以便异步响应
});

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

/**
 * 向内容脚本发送消息并与之通信
 * 
 * @param {string} action - 要执行的操作类型
 * @param {number} tabId - 目标标签页ID
 * @param {Object} data - 附加数据，默认为空对象
 * @returns {Promise<boolean|any>} 返回一个Promise，解析为以下值之一：
 *   - boolean类型true/false：当没有收到响应或发生错误时返回false
 *   - any类型：当收到响应且响应中没有success属性时，直接返回响应内容
 *   - boolean类型：当收到响应且响应中有success属性时，返回response.success的值
 */
async function sendMessageToContentScript(action, tabId, data = {}) {
  return new Promise((resolve) => {
    if (!tabId) {
      resolve(false);
      return;
    }

    chrome.tabs.sendMessage(tabId, {action, ...data}, (response) => {
      if (chrome.runtime.lastError) {
        console.error('消息发送错误:', chrome.runtime.lastError);
        resolve(false);
      } else {
        // 修改:根据需求调整响应处理逻辑
        if (response) {
          resolve(response.success !== undefined ? response.success : response);
        } else {
          resolve(false);
        }
      }
    });
  });
}

async function setPageSize(tabId, size) {
  await sendMessageToContentScript('clickElement', tabId, {
    xpath: '//li[contains(@class, "PGT_sizeChanger_")]//div[@data-testid="beast-core-select"]/div'
  });
  await sleep(1000);
  await sendMessageToContentScript('clickElement', tabId, {
    xpath: `//ul[starts-with(@class, "ST_dropdownPanel_")]/li/span[text()="${size}"]/parent::li`
  });
}

async function doRejectAllAdjustmentAndWait(tabId) {
  await sendMessageToContentScript('rejectAllAdjustment', tabId);
  while (true) {
    const rejectingResponse = await sendMessageToContentScript('checkIsRejectingAdjustment', tabId);
    if (rejectingResponse && !rejectingResponse.isRejecting) {
      console.log('所有调价对话框已处理完毕');
      break;
    }
    console.log('还有调价对话框正在处理中');
    await sleep(5000);
  }
}

async function handleAuthentication(tabId) {
  // 检查是否需要跳转到认证页面
  let clickResult = await sendMessageToContentScript('clickElement', tabId, {
    xpath: '//div[starts-with(@class, "authentication_goto__")]'
  });
  if (clickResult) {
    await sleep(5000);
    // 使用Promise包装chrome.tabs.query以便使用await
    const findAuthTab = () => {
      return new Promise((resolve) => {
        chrome.tabs.query({}, (tabs) => {
          let authTab = null;
          for (const tab of tabs) {
            if (tab.url && tab.url.startsWith('https://seller.kuajingmaihuo.com/settle/seller-login')) {
              authTab = tab;
              break;
            }
          }
          resolve(authTab);
        });
      });
    };
    
    // 等待查询结果
    const authTab = await findAuthTab();
    
    if (authTab) {
      // 激活认证标签页
      await new Promise(resolve => {
        chrome.tabs.update(authTab.id, {active: true}, resolve);
      });
      // 点击按钮“//button[./span[text()="确认授权并前往"]]”
      clickResult = await sendMessageToContentScript('clickElement', authTab.id, {
        xpath: '//button[./span[text()="确认授权并前往"]]'
      });
      if (clickResult) {
        await sleep(5000);
      }
      // 恢复原标签页为活动状态
      await new Promise(resolve => {
        chrome.tabs.update(tabId, {active: true}, resolve);
      });
      await sleep(500);
    }
  }

}

// 定义状态机的状态
const STATES = {
  INIT: 'init',
  LOGOUT: 'logout',
  LOGIN: 'login',
  HOMEPAGE: 'homepage',
  ORDER_MANAGE: 'order_manage',
  LIFE_CYCLE: 'life_cycle',
  GOODS_LIST: 'goods_list',
  ADJUST_PRICE: 'adjust_price',
  COMPETE_MANAGER: 'compete_manager',
  PRICE_FEEDBACK: 'price_feedback',
  EVALUATE_LIST: 'evaluate_list',
  EVALUATE_LIST_US: 'evaluate_list_us',
  EVALUATE_LIST_EU: 'evaluate_list_eu',
  COMPLETE: 'complete'
};

// 状态机配置
const stateConfig = {
  [STATES.INIT]: {
    url: 'https://seller.kuajingmaihuo.com/',
    next: STATES.LOGOUT,
    process: async (tabId) => {
      // 初始状态，只需要跳转页面
      return true;
    }
  },
  [STATES.LOGOUT]: {
    next: STATES.LOGIN,
    process: async (tabId) => {
      let logoutSuccess = true;
      let clickResult = await sendMessageToContentScript('clickElement', tabId, { 
        xpath: '//div[starts-with(@class, "account-info_mallLogo__")]' 
      });
      logoutSuccess &= clickResult;
      if (logoutSuccess) {
        await sleep(1000);
        clickResult = await sendMessageToContentScript('clickElement', tabId, { 
          xpath: '//div[starts-with(@class,"account-info_accountInfoSection_")]//div[starts-with(@class,"account-info_btnGroup__")]/div[2]' 
        });
        logoutSuccess &= clickResult;
      }
      if (logoutSuccess) {
        await sleep(1000);
        clickResult = await sendMessageToContentScript('clickElement', tabId, { 
          xpath: '//button[@data-testid="beast-core-modal-ok-button"]' 
        });
        logoutSuccess &= clickResult;
        await sleep(20000); // 等待页面重新加载
      }
      return logoutSuccess;
    }
  },
  [STATES.LOGIN]: {
    next: STATES.HOMEPAGE,
    process: async (tabId) => {
      let clickResult
      let setInputResult
      let loginSuccess = true;
      // 设置手机号码
      // setInputResult = await sendMessageToContentScript('setInputValue', tabId, {
      //   xpath: '//input[@placeholder="手机号码"]'
      // });
      // loginSuccess &= setInputResult;
      
      // if (loginSuccess) {
      //   await sleep(1000);
      //   // 设置密码
      //   setInputResult = await sendMessageToContentScript('setInputValue', tabId, {
      //     xpath: '//input[@placeholder="密码"]'
      //   });
      //   loginSuccess &= setInputResult;
      // } else {
      //   console.error('设置手机号码失败');
      // }
      
      if (loginSuccess) {
        await sleep(1000);
        clickResult = await sendMessageToContentScript('clickElement', tabId, { 
          xpath: '//label[@data-testid="beast-core-checkbox"]/div[1]' 
        });
        loginSuccess &= clickResult;
      }
      if (loginSuccess) {
        await sleep(2000);
        clickResult = await sendMessageToContentScript('triggerElementEvent', tabId, { 
          xpath: '//input[@id="usernameId"]',
          eventType: 'input'
        });
        loginSuccess &= clickResult;
        await sleep(500);
        clickResult = await sendMessageToContentScript('triggerElementEvent', tabId, { 
          xpath: '//input[@id="passwordId"]',
          eventType: 'input'
        });
        loginSuccess &= clickResult;
        await sleep(500);
        clickResult = await sendMessageToContentScript('clickElement', tabId, { 
          xpath: '//span[text()="登录"]/parent::button' 
        });
        // clickResult = await sendMessageToContentScript('clickElementByMouseSimulation', tabId, { 
        //   xpath: '//span[text()="登录"]/parent::button' 
        // });
        loginSuccess &= clickResult;
        await sleep(10000);
      }
      return loginSuccess;
    }
  },
  [STATES.HOMEPAGE]: {
    next: STATES.ORDER_MANAGE,
    process: async (tabId) => {
      await sendMessageToContentScript('previewHomePageProcess', tabId);
      await sleep(10000);
      return true;
    }
  },
  [STATES.ORDER_MANAGE]: {
    url: 'https://agentseller.temu.com/stock/fully-mgt/order-manage',
    next: STATES.LIFE_CYCLE,
    process: async (tabId) => {
      // 消除提示框
      let clickResult
      clickResult = await sendMessageToContentScript('clickElement', tabId, { 
        xpath: '//div[@data-testid="beast-core-modal-inner"]//button[./span[text()="立即发货"]]/following-sibling::button[./span[text()="我知道了"]]' 
      });
      if (clickResult) {
        await sleep(1000);
      }
      // 获取待创建数量并处理
      const pendingCountResponse = await sendMessageToContentScript('previewGetPendingCount', tabId);
      if (pendingCountResponse && pendingCountResponse.count > 0) {
        await sendMessageToContentScript('clickElement', tabId, {
          xpath: '//div[@data-testid="beast-core-tab-itemLabel-wrapper" and ./div[@data-testid="beast-core-tab-itemLabel" and starts-with(text(), "待创建")]]'
        });
        await sleep(10000);

        clickResult = await sendMessageToContentScript('clickElement', tabId, {
          xpath: '//thead//label[.//input[@type="checkbox"]]'
        });
        if (clickResult) {
          await sleep(2000);
          clickResult = await sendMessageToContentScript('clickElement', tabId, {
            xpath: '//button[./span[text()="批量创建备货单"]]'
          });
          if (clickResult) {
            await sleep(1000);
            clickResult = await sendMessageToContentScript('clickElement', tabId, {
              xpath: '//button[./span[text()="确认"]]'
            });
            if (clickResult) {
              await sleep(10000);
              await sendMessageToContentScript('clickElement', tabId, {
                xpath: '//div[@data-testid="beast-core-modal" and .//div[contains(normalize-space(.), "个备货单创建备货单成功")]]//button[./span[text()="我知道了"]]'
              });
              await sleep(1000);
            }
          }
        }
      }
      return true;
    }
  },
  [STATES.LIFE_CYCLE]: {
    url: 'https://agentseller.temu.com/newon/product-select',
    next: STATES.GOODS_LIST,
    process: async (tabId) => {
      // 批量确认商品信息
      await sendMessageToContentScript('clickElement', tabId, {
        xpath: '//div[@class="use-quick-field_tsx_card__isidn" and ./span[text()="商品信息待确认"] and not(./div[starts-with(@class, "use-quick-field_tsx_clickIcon__")])]'
      });
      await sleep(10000);
      await sendMessageToContentScript('clickElement', tabId, {
        xpath: '//thead[@data-testid="beast-core-table-middle-thead"]//label[@data-testid="beast-core-checkbox"]'
      });
      await sleep(1000);
      await sendMessageToContentScript('clickElement', tabId, {
        xpath: '//button[@data-testid="beast-core-button" and ./span[text()="批量确认商品信息"]]'
      });
      await sleep(2000);
      await sendMessageToContentScript('clickElement', tabId, {
        xpath: '//div[starts-with(@class, "body-module__modal__") and .//div[starts-with(normalize-space(.), "要批量确认本次勾选的")]]//button[./span[text()="确认"]]'
      });
      // 检查是否有价格待确认的商品
      // 如果有，则逐个降价0.05元
      const countResponse = await sendMessageToContentScript('previewGetPricesToConfirm', tabId);
      if (countResponse && countResponse.count > 0) {
        await sendMessageToContentScript('clickElement', tabId, {
          xpath: '//div[starts-with(@class,"use-quick-field_tsx_container")]//div[./span[text()="价格待确认"]]'
        });
        await sleep(10000);
        // 然后进行申报价调整
        await adjustPrice()
      }
      return true;
    }
  },
  [STATES.GOODS_LIST]: {
    url: 'https://agentseller.temu.com/goods/list',
    next: STATES.ADJUST_PRICE,
    process: async (tabId) => {
      // 处理弹窗
      const modalHandled = await sendMessageToContentScript('previewHandleGoodsListModal', tabId);
      if (modalHandled) {
        await sleep(10000);
      }
      return true;
    }
  },
  [STATES.ADJUST_PRICE]: {
    url: 'https://agentseller.temu.com/main/adjust-price-manage/order-price',
    next: STATES.COMPETE_MANAGER,
    process: async (tabId) => {
      // 获取待确认改价并处理
      while (true) {
        // 有可能大于100条，需要按页处理
        const pendingCountResponse = await sendMessageToContentScript('previewGetAdjustmentCount', tabId);
        if (!pendingCountResponse || pendingCountResponse.count == 0) {
          break;
        }
        await sendMessageToContentScript('clickElement', tabId, {
          xpath: '//div[@data-testid="beast-core-tab-itemLabel-wrapper" and ./div[@data-testid="beast-core-tab-itemLabel" and starts-with(text(), "待卖家确认")]]'
        });
        await sleep(10000);

        // 每页设置为100条
        await setPageSize(tabId, 100);
        await sleep(5000);

        let clickResult = await sendMessageToContentScript('clickElement', tabId, {
          xpath: '//thead//label[.//input[@type="checkbox"]]'
        });
        if (clickResult) {
          await sleep(2000);
          clickResult = await sendMessageToContentScript('clickElement', tabId, {
            xpath: '//button[./span[text()="批量处理"]]'
          });
          if (clickResult) {
            await sleep(3000);
            await doRejectAllAdjustmentAndWait(tabId);
          }
        }
      }
      return true;
    }
  },
  [STATES.COMPETE_MANAGER]: {
    url: 'https://agentseller.temu.com/newon/compete-manager',
    next: STATES.PRICE_FEEDBACK,
    process: async (tabId) => {
      return true;
    }
  },
  [STATES.PRICE_FEEDBACK]: {
    url: 'https://agentseller.temu.com/main/adjust-price-manage/feedback',
    next: STATES.EVALUATE_LIST,
    process: async (tabId) => {
      // 检查是否有待跟价商品
      const priceFeedbackResult = await sendMessageToContentScript('previewCheckPriceFeedback', tabId);
      if (priceFeedbackResult && priceFeedbackResult.hasPending) {
        await sendMessageToContentScript('previewAlertUser', tabId, { 
          message: "有待跟价商品！" 
        });
        // 这里我们不直接返回false，而是继续流程到结束状态
        return false;
      }
      return true;
    }
  },
  [STATES.EVALUATE_LIST]: {
    url: 'https://agentseller.temu.com/main/evaluate/evaluate-list',
    next: STATES.EVALUATE_LIST_US,
    process: async (tabId) => {
      return true;
    }
  },
  [STATES.EVALUATE_LIST_US]: {
    url: 'https://agentseller-us.temu.com/main/evaluate/evaluate-list',
    next: STATES.EVALUATE_LIST_EU,
    process: async (tabId) => {
      await handleAuthentication(tabId);
      await sleep(5000);
      await doRejectAllAdjustmentAndWait(tabId);
      return true;
    }
  },
  [STATES.EVALUATE_LIST_EU]: {
    url: 'https://agentseller-eu.temu.com/main/evaluate/evaluate-list',
    next: STATES.COMPLETE,
    process: async (tabId) => {
      await handleAuthentication(tabId);
      await sleep(5000);
      await doRejectAllAdjustmentAndWait(tabId);
      return true;
    }
  },
  [STATES.COMPLETE]: {
    process: async (tabId) => {
      await sendMessageToContentScript('previewAlertUser', tabId, { message: 'previewAllPages流程完成' });
      console.log('所有状态处理完成');
      return true;
    }
  }
};

async function previewAllPages(tabId) {
  console.log('开始执行previewAllPages流程...');
  const pageLoadDelay = 30000;

  try {
    let currentState = STATES.ORDER_MANAGE;
    
    while (currentState !== STATES.COMPLETE) {
      const config = stateConfig[currentState];
      console.log(`处理状态: ${currentState}`);
      
      // 如果有URL，跳转到该URL
      if (config.url) {
        await chrome.tabs.update(tabId, { url: config.url });
        await sleep(pageLoadDelay);
      }

      // 如果有调价对话框，进行处理
      await doRejectAllAdjustmentAndWait(tabId);

      // 如果有核价对话框，关闭他
      await sendMessageToContentScript('clickElement', tabId, {
        xpath: '//div[@data-testid="beast-core-modal" and .//div[text()="您的商品需重新报价"]]//button[./span[text()="稍后再说"]]'
      });
      await sleep(2000);
      
      // 执行当前状态的处理逻辑
      const success = await config.process(tabId);
      if (!success) {
        console.error(`状态 ${currentState} 处理失败`);
        break;
      }

      // 如果有调价对话框，进行处理。agentseller-eu.temu.com是登录后才有调价对话框
      await doRejectAllAdjustmentAndWait(tabId);

      // 如果仍然有对话框，就等待直到被处理
      while (true) {
        const stillDialogCount = await sendMessageToContentScript('getElementCount', tabId, {
          xpath: '//div[@data-testid="beast-core-modal-body"]'
        });
        if (stillDialogCount.count === 0) {
          break;
        }
        console.log('等待对话框被处理...');
        await sleep(5000);
      }
      
      // 转移到下一个状态
      currentState = config.next;
    }
    await sendMessageToContentScript('previewAlertUser', tabId, { 
      message: "previewAllPages流程完成!" 
    });

    console.log('previewAllPages流程完成!');
    return;
  } catch (error) {
    console.error('previewAllPages流程出错:', error);
  }
}

async function adjustPrice() {
  console.log('开始执行自动调价流程...');

  async function adjustPriceProcess() {
    const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
    if (!tab?.id) {
      console.error('没有找到活动标签');
      return;
    }
    const tabId = tab.id;
    let adjustedCount = 0;
    try {
      // 发送显示调价进度消息
      await chrome.tabs.sendMessage(tabId, {action: 'showAdjustmentInProgress', count: adjustedCount});

      let hasMore = true;
      while (hasMore) {
        // 1. 点击"查看并确认申报价格"按钮
        const clickSuccess = await sendMessageToContentScript('clickViewPriceButton', tabId);
        if (!clickSuccess) {
          console.log('没有找到更多"查看并确认申报价格"按钮');
          hasMore = false;
          break;
        }

        // 2. 等待对话框加载完成
        await sleep(2000);

        // 3. 选择"重新调整报价"选项
        const selectSuccess = await sendMessageToContentScript('selectAdjustOption', tabId);
        if (!selectSuccess) {
          console.log('选择调整选项失败');
          break;
        }
        await sleep(1000);

        // 4. 计算并填写新价格
        const fillSuccess = await sendMessageToContentScript('calculateAndFillPrices', tabId);
        if (!fillSuccess) {
          console.log('填写价格失败');
          break;
        }
        await sleep(2000);

        // 5. 提交调整后的价格
        const submitSuccess = await sendMessageToContentScript('submitAdjustedPrices', tabId);
        if (!submitSuccess) {
          console.log('提交价格失败');
          break;
        }

        adjustedCount++;

        // 7. 等待10秒后继续循环
        await sleep(10000);
      }

      console.log('自动调价流程完成');
      // 发送完成消息给content script
      // chrome.tabs.sendMessage(tabId, {
      //   action: 'priceAdjustmentComplete',
      //   adjustedCount: adjustedCount
      // });
      
      // 发送隐藏调价进度消息
      // try {
      //   await chrome.tabs.sendMessage(tabId, {action: 'hideAdjustmentInProgress'});
      // } catch (e) {
      //   console.error('Failed to send hideAdjustmentInProgress message:', e);
      // }
    } catch (error) {
      console.error('自动调价流程出错:', error);
      
      // 出错时也尝试隐藏调价进度提示
      try {
        await chrome.tabs.sendMessage(tabId, {action: 'hideAdjustmentInProgress'});
      } catch (e) {
        console.error('Failed to send hideAdjustmentInProgress message:', e);
      }
    }
  }

  await adjustPriceProcess();
}

const remoteServerIps = [
  '47.120.6.166',
  '47.120.71.212',
  '106.52.158.179',
  '43.138.240.186',
];
const remoteServerIps_https = [
  // '60.215.128.117:40338',
];

const localServerIps = [
  '192.168.0.116'
];

const serverPort = '10999';

async function handleMongoDBLinkUpdate(tabId) {
  chrome.tabs.sendMessage(tabId, {
    action: 'getMongoDBLink'
  }, (response) => {
    if (chrome.runtime.lastError) {
      console.error('Error sending message:', chrome.runtime.lastError);
      return;
    }
    
    const mongoDBLink = response?.link?.trim();
    if (!mongoDBLink) {
      console.error('No MongoDB link found');
      return;
    }
    
    // 发送到4个预设服务器
    const servers_http = remoteServerIps.map(ip => `http://${ip}:${serverPort}/update_mongodb_link`);
    const servers_https = remoteServerIps_https.map(ip => `https://${ip}/update_mongodb_link`);

    const servers = [...servers_http, ...servers_https];
    
    Promise.all(servers.map(async server => {
      return fetch(server, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ url: mongoDBLink })
      })
      .then(response => {
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        result = response.text();
        console.log(`${server} 响应成功`, result);
        return result;
      })
      .then(() => {
        // POST成功后发送GET请求验证
        return fetch(server, {
          method: 'GET'
        });
      })
      .then(response => {
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
      })
      .then(data => {
        // 检查GET到的值是否与POST的值相同
        if (data.url === mongoDBLink) {
          return true; // 验证成功
        } else {
          throw new Error('Verification failed: returned URL does not match');
        }
      })
      .catch(err => {
        console.error(`Failed to process ${server}:`, err);
        return false; // 标记为失败
      });
    }))
    .then(async (results) => {
      // 计算成功个数
      const successCount = results.filter(result => result === true).length;
      
      // 通知popup显示完成提示，带上成功个数
      await chrome.runtime.sendMessage({
        action: 'showMongoDBUpdateComplete',
        successCount: successCount,
        totalServers: servers.length
      });
    });
  });
}


async function executeServerCommand(servers, command, completeMessage) {
  Promise.all(servers.map(async server => {
    return fetch(server+"/"+command, {
      method: 'GET'
    })
    .then(response => {
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      return true;
    })
    .catch(err => {
      console.error(`Failed to process ${server}:`, err);
      return false; // 标记为失败
    });
  }))
  .then(async (results) => {
    // 计算成功个数
    const successCount = results.filter(result => result === true).length;
    
    // 通知popup显示完成提示，带上成功个数
    await chrome.runtime.sendMessage({
      action: completeMessage,
      successCount: successCount,
      totalServers: servers.length
    });
  });

}

async function reloginSeller(tabId) {
  // 发送到4个预设服务器
  const servers = [...remoteServerIps, ...localServerIps].map(ip => `http://${ip}:${serverPort}`);

  await executeServerCommand(servers, 'relogin_temu_seller', 'reloginSellerStarted');
}

async function getSalesData() {
  const servers = [...remoteServerIps, ...localServerIps].map(ip => `http://${ip}:${serverPort}`);

  await executeServerCommand(servers, 'fetch_realtime_sells', 'fetchSalesDataComplete');
}

async function startDailyCrawl() {
  const servers = [...remoteServerIps, ...localServerIps].map(ip => `http://${ip}:${serverPort}`);

  await executeServerCommand(servers, 'start_daily_crawl', 'startDailyCrawlComplete');
}

async function restartServerTask() {
  const servers = [...remoteServerIps, ...localServerIps].map(ip => `http://${ip}:${serverPort}`);

  await executeServerCommand(servers, 'restart_server_task', 'restartServerTaskComplete');
}

async function pullTemuSpiders() {
  const servers = [...remoteServerIps, ...localServerIps].map(ip => `http://${ip}:${serverPort}`);

  await executeServerCommand(servers, 'pull_temu_spiders', 'pullTemuSpidersComplete');
}

async function addSerialNumber(tabId, spuIds, serialNumber) {
  console.log('开始执行添加序列号流程...');
  
  // 1. 初始检查
  const tab = await chrome.tabs.get(tabId);
  if (tab.url !== 'https://agentseller.temu.com/govern/information-supplementation') {
    console.error('当前页面URL不匹配，期望: https://agentseller.temu.com/govern/information-supplementation, 实际:', tab.url);
    return { success: false, error: '当前页面URL不匹配' };
  }

  let successCount = 0;
  let skipCount = 0;
  // 针对每个spuId执行操作
  for (const spuId of spuIds) {
    console.log('处理 SPU ID:', spuId);
    
    // 2.1 查询操作
    // 清空spuId输入框
    await sendMessageToContentScript('clearInputValue', tabId, {
      xpath: '//input[@id="spuId"]'
    });
    await sleep(200);
    
    // 填入当前spuId
    await sendMessageToContentScript('fillInputByKeys', tabId, {
      xpath: '//input[@id="spuId"]',
      value: spuId
    });
    await sleep(200);
    
    // 点击查询按钮
    await sendMessageToContentScript('clickElement', tabId, {
      xpath: '//button[./span[text()="查 询"]]'
    });
    await sleep(5000);
    
    // 2.2 编辑操作
    // 检查编辑按钮数量
    const editButtonCount = await sendMessageToContentScript('getElementCount', tabId, {
      xpath: '//button[./span[text()="编辑"]]'
    });
    
    if (editButtonCount.count !== 1) {
      console.error('编辑按钮数量不匹配，期望: 1, 实际:', editButtonCount.count);
      continue;
    }
    // 点击编辑按钮
    await sendMessageToContentScript('clickElement', tabId, {
      xpath: '//button[./span[text()="编辑"]]'
    });
    await sleep(5000);
    
    // 2.3 页面操作
    // 滚动到页面底部
    await sendMessageToContentScript('scrollToBottom', tabId, {
      xpath: '//div[@class="rocket-drawer-body"]'
    });
    await sleep(1000);
    
    // 2.4 序列号检查
    const isSerialNumberExists = await sendMessageToContentScript('checkSerialNumberExists', tabId, {
      xpath: '//div[@class="rocket-row"]//input[contains(@class,"rocket-input") and contains(@class,"rocket-input-sm")]',
      serialNumber: serialNumber
    });
    
    if (isSerialNumberExists.exists) {
      // 2.5 情况1: 序列号已存在
      await sendMessageToContentScript('clickElement', tabId, {
        xpath: '//button[./span[text()="取 消"]]'
      });
      await sleep(1000);
      // 继续处理下一个spuId
      skipCount++;
      continue;
    } else {
      // 2.5 情况2: 序列号不存在
      // 点击新增按钮
      await sendMessageToContentScript('clickElement', tabId, {
        xpath: '//a[normalize-space(.)="新增商品识别码"]'
      });
      await sleep(1000);
      
      // 找到最后一个输入框并填入序列号
      await sendMessageToContentScript('fillInputByKeys', tabId, {
        xpath: '(//div[@class="rocket-row"]//input[contains(@class,"rocket-input") and contains(@class,"rocket-input-sm")])[last()]',
        value: serialNumber
      });
      await sleep(1000);
      
      // 点击确认按钮
      await sendMessageToContentScript('clickElement', tabId, {
        xpath: '//button[./span[text()="确 认"]]'
      });
      await sleep(5000);
      // 缺少其它信息可能导致无法提交，这里暂时跳过
      const cancelButtonCount = await sendMessageToContentScript('getElementCount', tabId, {
        xpath: '//button[./span[text()="取 消"]]'
      });
      if (cancelButtonCount.count === 1) {
        await sendMessageToContentScript('clickElement', tabId, {
          xpath: '//button[./span[text()="取 消"]]'
        });
        await sleep(1000);
      } else {
        successCount++;
      }
      // 继续处理下一个spuId
    }
  }
  const failCount = spuIds.length - successCount - skipCount;
  await sendMessageToContentScript('previewAlertUser', tabId, { 
    message: `所有SPU ID处理完成，成功添加序列号的SPU数量: ${successCount}，跳过的SPU数量：${skipCount}，失败的SPU数量: ${failCount}`
  });

  
  console.log('所有SPU ID处理完成');
  return { success: true };
}

/**
 * 从本地服务器获取SKU成本价
 * 
 * @param {string} skc - 商品SKC编码
 * @param {string} sku - 商品SKU编码
 * @returns {Promise<Object>} 返回包含成本价的对象
 */
async function fetchSkuCost(skc, sku) {
  try {
    // 构建请求URL
    const url = `http://localhost:10999/get_sku_cost?skc=${encodeURIComponent(skc)}&sku=${encodeURIComponent(sku)}`;
    
    // 发送请求获取成本价
    const response = await fetch(url);
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const data = await response.json();
    console.log(`获取到SKU ${sku} 的成本价:`, data);
    return data;
  } catch (error) {
    console.error(`获取SKU ${sku} 成本价时出错:`, error);
    throw error;
  }
}

async function fetchSkuCostsAndStocks(skuList) {
  try {
    // 构造请求数据
    const requestData = {
      skuList: skuList
    };

    // 发送单个 POST 请求获取所有 SKU 的成本和库存数据
    const response = await fetch('http://localhost:10999/get_sku_costs_and_stocks', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(requestData)
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();

    const results = {};
    for (const item of data.results) {
      results[`${item.skc}_${item.sku}`] = item;
    }
    console.log('获取到所有 SKU 的成本和库存数据:', results);
    return results;
  } catch (error) {
    console.error('获取 SKU 成本和库存数据时出错:', error);
    throw error;
  }
}
